package com.tang.mybatis.binding;

import com.tang.mybatis.mapping.MappedStatement;
import com.tang.mybatis.session.SqlSession;
import lombok.Data;

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Collection;

/**
 * @author Tang
 * @classname MapperProxy
 * @description [  ]
 * @date 2022/4/6 23:45
 */
@Data
public class MapperProxy<T> implements InvocationHandler, Serializable {

    private Class<T> mapperInterface;

    private SqlSession sqlSession;

    public MapperProxy(Class<T> mapperInterface, SqlSession sqlSession) {
        this.mapperInterface = mapperInterface;
        this.sqlSession = sqlSession;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (Object.class.equals(method.getDeclaringClass())) {
            return method.invoke(this, args);
        }
        return this.execute(method, args);
    }

    private Object execute(Method method, Object[] args) {
        String statementId = this.mapperInterface.getName() + "." + method.getName();
        MappedStatement mappedStatement = this.sqlSession.getConfiguration().getMappedStatement(statementId);

        Object result = null;
        switch (mappedStatement.getSqlType()) {
            case SELECT:
                Class<?> returnType = method.getReturnType();
                if (Collection.class.isAssignableFrom(returnType)) {
                    // statementId = 全类名 + 方法名
                    result = this.sqlSession.selectList(statementId,args);
                }else {
                    result = this.sqlSession.selectOne(statementId, args);
                }
                break;
            case DELETE:

                break;
            case INSERT:

                break;
            case UPDATE:

                break;
            default:
                break;
        }
        return result;
    }
}